<?php


namespace app\api\controller\v22;


use app\api\controller\v2\Auth;
use app\common\cachemodel\Goods as GoodsCacheModel;
use app\common\cachemodel\Recode;
use app\common\cachemodel\Rectification as RectificationCacheModel;
use app\common\cachemodel\RectificationEvent;
use app\common\cachemodel\ZhunleActivity;
use app\common\cachemodel\ZhunleUserAccount;
use app\common\cachemodel\ZlcrCustomReportGoods;
use app\common\cachemodel\ZlcrTag;
use app\common\lib\exception\ApiException;
use app\common\lib\SensorsData;
use app\common\lib\Util;
use Exception;
use think\Log;

/**
 * @version 2.5.1
 * Class Goods
 * @package app\api\controller\v22
 */
class Goods extends Auth
{
    protected $notice = [
        1 => '以下所有时间均为东八区哦',
        2 => '下单前请务必核对好购买信息',
        3 => '下单前请务必核对好购买信息',
        4 => '下单前请务必核对好购买信息',
        5 => '下单前请务必核对好购买信息',
        6 => '下单前请务必核对好购买信息',
        7 => '下单前请务必核对好购买信息',
        8 => '下单前请务必核对好购买信息',
        15 => '下单前请务必核对好购买信息',
        16 => '下单前请务必核对好购买信息',
        17 => '下单前请务必核对好购买信息',
    ];

    protected $pay_pop_tips = "本服务由准了APP提供，购买该服务以下服务声明需知：\n\n1、本服务由准了官方平台分发至平台专业占星师，由于服务含有为付费者定作、定制属性，超出规定时间将扣除相应费用，不支持无理由取消订单退款\n\n2、因本服务有定制特殊性，下单后派发队列中未被占星师接单可取消订单，如已派发被占星师接单，15分钟内取消订单退款订单金额90%，10%订单金额手续费赔付占星师，如超过15分钟则不可取消订单\n\n3、本报告内容由占星师结合提问者星盘定制产出，因测算维度技法不同，内容理性判断仅供参考，请勿过于依赖，事件的改善走向都由提问者本身判断决定";

    /**
     * 获取商品信息
     * @throws Exception
     */
    public function read()
    {
        $type = input('param.type/d', 0);
        if (!$type)
        {
            return show(config('code.error'), '未知的商品');
        }
        $gid = input('param.gid/d', 0);
        $rid = input('param.rid/d', 0);
        $rid2 = input('param.rid2/d', 0);
        $now_time = time();
        $start_time = input('param.start_time/s', '');
        //检验请求参数
        $res = $this->checkReadParam(['type' => $type, 'gid' => $gid, 'rid' => $rid, 'rid2' => $rid2, 'start_time' => $start_time]);
        if ($res !== true)
        {
            return show(config('code.error'), $res);
        }
        // if (!in_array($type, [6, 8, 9, 18], true) && !$this->user['rid'])
        // {
        //     return show(406, '请添加自己的档案');
        // }
        $notice = $this->notice[$type];
        //获取定制报告商品数据
        if ($type === 15)
        {
            $goods = (new ZlcrCustomReportGoods())->batchGetInfoByIds($gid);
            $goods_info = $this->resetCustomQuestionGoods($goods);
        } else//获取其他商品数据
        {
            $GoodsCacheModel = new GoodsCacheModel();
            $goods = $GoodsCacheModel->GoodsTypeInfo($type);
            $goods_info = $GoodsCacheModel->resetGoodsInfo($this, $type, $goods, $rid, $rid2, $start_time, $gid);
//            // 学业报告临时活动  2020-07-23 18:00:00   ～   2020-09-05 23:59:59
//            if ((int)$type === 7 && $now_time >= 1595498400 && $now_time <= 1599321599)
//            {
//                $notice = '单独解锁学业报告才能享受九折优惠哦';
//            }
        }
        // 神策数据打点
        if ($goods && $goods_info)
        {
            $distinctId = $this->request->header('distinct-id', '');
            if ($distinctId)
            {
                switch ($type)
                {
                    case 1:#校准生辰
                        // 校准生辰默认为自己的档案
                        $recordInfo = (new Recode())->getInfoById($this->user['rid'], ['id', 'uid', 'name', 'year', 'month', 'day', 'is_summer']);
                        // 获取校准生辰  获取最新的未支付订单 即刚下单的校准生辰数据
                        $rectification = (new RectificationCacheModel())
                            ->field('id,start_time,end_time,is_del,status')
                            ->where(['uid' => $this->user['id'], 'rid' => $this->user['rid'], 'is_del' => 0, 'status' => 0])
                            ->order('id', 'DESC')
                            ->findOrFail()
                            ->toArray();
                        // 获取校准生辰所有事件
                        $events = (new RectificationEvent())->batchGetInfoByIds([$rectification['id']], ['id', 'time', 'type', 'desc']);
                        $eventIdList = [];
                        foreach ($events as $v)
                        {
                            $eventIdList[] = (string)$v['id'];
                        }
                        #神策打点 53 校准生辰下单 RectificationBuy
                        $sensorsTrackData = [
                            'record_name' => $recordInfo['name'],
                            'record_id' => $this->user['rid'],
                            'birth_year' => $recordInfo['year'],
                            'birth_month' => $recordInfo['month'],
                            'birth_day' => $recordInfo['day'],
                            'start_time' => date('Y-m-d H:i:s', $rectification['start_time']),
                            'end_time' => date('Y-m-d H:i:s', $rectification['end_time']),
                            'is_summer' => $recordInfo['is_summer'] ? true : false,
                            'event_num' => count($eventIdList),
                            'event_id_list' => $eventIdList,
                            'is_success' => true,
                            'failed_reson' => '',
                        ];
                        SensorsData::track($this->user['id'], true, 'RectificationBuy', $sensorsTrackData);
                        break;
                    case 2:#每日运势
                        $recordInfo = (new Recode())->getInfoById($rid, ['id', 'uid', 'name']);
                        #神策打点 33 日/月/年运势提交购买 RecordFortuneBuy
                        $sensorsTrackData = [
                            'record_name' => $recordInfo['name'],
                            'record_id' => $rid,
                            'fortune_type' => '每日运势',// 运势类型
                            'fortune_time' => $start_time,// 选择时间
                        ];
                        SensorsData::track($this->user['id'], true, 'RecordFortuneBuy', $sensorsTrackData);
                        break;
                    case 3:#月度运势
                        $recordInfo = (new Recode())->getInfoById($rid, ['id', 'uid', 'name']);
                        #神策打点 33 日/月/年运势提交购买 RecordFortuneBuy
                        $sensorsTrackData = [
                            'record_name' => $recordInfo['name'],
                            'record_id' => $rid,
                            'fortune_type' => '月度运势',// 运势类型
                            'fortune_time' => $start_time,// 选择时间
                        ];
                        SensorsData::track($this->user['id'], true, 'RecordFortuneBuy', $sensorsTrackData);
                        break;
                    case 4:#年度运势
                        $recordInfo = (new Recode())->getInfoById($rid, ['id', 'uid', 'name']);
                        #神策打点 33 日/月/年运势提交购买 RecordFortuneBuy
                        $sensorsTrackData = [
                            'record_name' => $recordInfo['name'],
                            'record_id' => $rid,
                            'fortune_type' => '年度运势',// 运势类型
                            'fortune_time' => $start_time,// 选择时间
                        ];
                        SensorsData::track($this->user['id'], true, 'RecordFortuneBuy', $sensorsTrackData);
                        break;
                    case 5:#幸运之城
                        $recordInfo = (new Recode())->getInfoById($rid, ['id', 'uid', 'name']);
                        #神策打点 45 幸运之城选择解锁 LuckyMapBuy
                        $sensorsTrackData = [
                            'record_name' => $recordInfo['name'],
                            'record_id' => $rid,
                            'unlock_type' => '',
                            'goods_name' => '',
                            'goods_id' => $gid,
                        ];
                        if ($gid === 19)
                        {
                            $sensorsTrackData['unlock_type'] = '打包解锁';
                            $sensorsTrackData['goods_name'] = '幸运之城全内容打包解锁';
                        } else
                        {
                            $sensorsTrackData['unlock_type'] = '指定解锁';
                            foreach ($goods_info['goods_data'] as $v)
                            {
                                if ($gid === $v['gid'])
                                {
                                    $sensorsTrackData['goods_name'] = $v['name'];
                                    break;
                                }
                            }
                        }
                        SensorsData::track($this->user['id'], true, 'LuckyMapBuy', $sensorsTrackData);
                        break;
                    case 7:#一生报告
                        $recordInfo = (new Recode())->getInfoById($rid, ['id', 'uid', 'name']);
                        #神策打点 38 一生报告提交购买 NatalReportBuy
                        $sensorsTrackData = [
                            'record_name' => $recordInfo['name'],
                            'record_id' => $rid,
                            'report_name' => '未知类型',//报告类型
                        ];
                        switch ($gid)
                        {
                            case 39:
                                $sensorsTrackData['report_name'] = '恋爱格局预测报告';
                                break;
                            case 40:
                                $sensorsTrackData['report_name'] = '婚姻格局预测报告';
                                break;
                            case 41:
                                $sensorsTrackData['report_name'] = '财富格局预测报告';
                                break;
                            case 42:
                                $sensorsTrackData['report_name'] = '事业格局预测报告';
                                break;
                            case 52:
                                $sensorsTrackData['report_name'] = '学业格局预测报告';
                                break;
                        }
                        SensorsData::track($this->user['id'], true, 'NatalReportBuy', $sensorsTrackData);
                        break;
                    case 15:#定制报告
                        try
                        {
                            #神策打点 97 定制报告去下单 CustomReportBuy
                            $tagName = (new ZlcrTag())->getInfoByIdsInData([$goods[$gid]['tid']], null, null);
                            $sensorsTrackData = [
                                'question_type' => $tagName[$goods[$gid]['tid']]['tag_name'], // 问题类型
                                'question_name' => $goods[$gid]['question_name'], // 问题名称
                            ];
                            SensorsData::track($this->user['id'], true, 'CustomReportBuy', $sensorsTrackData);
                        }
                        catch (\Exception $e)
                        {
                            Log::write('神策打点 CustomReportBuy 失败：' . $e->getMessage() . '[' . $e->getFile() . ':' . $e->getLine() . ']', 'error');
                        }
                        break;
                    case 17:
                        $recordInfo1 = (new Recode())->getInfoById($rid, ['id', 'uid', 'name']);
                        $recordInfo2 = (new Recode())->getInfoById($rid2, ['id', 'uid', 'name']);
                        #神策打点 91 合盘报告提交 SynastryReportBuy
                        $sensorsTrackData = [
                            'report_name' => '',// 报告类型
                            'time_range' => '',// 计算周期
                            'begin_time' => date('Y-m-d H:i:s', strtotime($start_time . '-01')),// 开始时间
                            'record1_name' => $recordInfo1['name'],// 档案名称1
                            'record1_id' => $rid,// 档案ID1
                            'record2_name' => $recordInfo2['name'],// 档案名称2
                            'record2_id' => $rid2,// 档案ID2
                        ];
                        $synastryReportConfig = config('synastryreport');
                        $relations = ['', '暗恋对象', '正在热恋', '已经分手', '步入婚姻'];
                        foreach ($synastryReportConfig[1]['good_list'] as $k => $v)
                        {
                            if ($gid === $k)
                            {
                                $sensorsTrackData['report_name'] = $relations[$v['relation_id']];
                                $sensorsTrackData['time_range'] = $v['name_desc'];
                            }
                        }
                        SensorsData::track($this->user['id'], true, 'SynastryReportBuy', $sensorsTrackData);
                        break;
                    default:
                        break;
                }
            }
            $goods_info['notice'] = $notice;
            return show(config('code.success'), '获取成功', $goods_info);
        }
        return show(config('code.error'), '商品不存在');
    }

    /**
     * 重组定制报告商品数据
     * @param $goods
     * @return array
     * @throws Exception
     */
    private function resetCustomQuestionGoods($goods)
    {
        $gid = current(array_keys($goods));
        $goods = current($goods);
        $user_coin = (new ZhunleUserAccount())->getUserCoinFromCache($this->user['id']);  // 账户信息

        // 查询是否开启折扣活动，获取折扣信息
        $activeData = [];
        // 定制报告商品不支持VIP内部价格，所以不需要查询vip信息
        $activing = (new ZhunleActivity())->getActivingGood(15, $gid);
        if ($activing)
        {
            $activeData['name'] = $activing['name'];
            $activeData['discount'] = sprintf('%.2f', $activing['attr']);
        }

        return [
            'goods_data' => [
                0 => [
                    'gid' => $gid,
                    'name' => $goods['question_name'],
                    'des' => '',
                    'price' => $goods['price'],
                ],
            ],
            'active_data' => $activeData,
            'coupon_data' => [
                'usable_num' => 0,
                'name' => '优惠券'
            ],
            'has_mobile' => 1,// TODO 暂时关闭下单验证手机号逻辑
            'coin_pwd_status' => (isset($user_coin['password']) && $user_coin['password']) ? 1 : 0,  // 是否设置了支付密码
            'coin_num' => (int)($user_coin['balance'] ?? 0),// 准币余额
            'pay_pop_tips' => $this->pay_pop_tips
        ];
    }

    /**
     * 检测获取商品信息接口请求参数是否正确
     * @param $param
     * @return bool|string
     * @throws ApiException
     */
    private function checkReadParam($param)
    {
        switch (true)
        {
            case !in_array($param['type'], [1, 2, 3, 4, 5, 6, 7, 8, 15, 16, 17], true):
                $msg = '未知的商品';
                break;
            case  in_array($param['type'], [6, 15, 16, 17], true) && !$param['gid']:
                $msg = '缺少商品参数';
                break;
            case in_array($param['type'], [5, 7], true) && !$param['rid']:
                $msg = '档案未知';
                break;
            default :
                $msg = true;
                break;
        }
        if (in_array($param['type'], [2, 3, 4, 12, 17], true) && !$param['start_time'])
        {
            return '请选择开始时间';
        }
        //检验时间格式
        if ($param['start_time'])
        {
            Util::FormatFortuneTime($param['type'], $param['start_time']);
        }
        if ($param['type'] === 17 && (!$param['rid'] || !$param['rid2']))
        {
            return '服务异常，请稍后重试～';
        }
        return $msg;

    }
}
